package com.lemon.core.base.util;

/**
 * 隐藏部分信息工具类
 *
 * @author pan
 * @since 2017-11-17
 */
public class MaskUtils {
    private MaskUtils() {
    }

    /**
     * 隐藏手机号
     *
     * @param cellphoneNo 手机号
     * @return 隐藏手机号
     */
    public static String maskCellphone(String cellphoneNo) {
        if (cellphoneNo == null || cellphoneNo.trim().length() != 11) {
            return cellphoneNo;
        }
        return cellphoneNo.substring(0, 3) + "****" + cellphoneNo
            .substring(cellphoneNo.length() - 4);
    }

    /**
     * 隐藏邮箱信息
     *
     * <pre>
     * MaskUtils.maskEmail("foo@bar.com")        = "foo@***.com"
     * MaskUtils.maskEmail("foo@bar.vip.com")    = "foo@***.com"
     * MaskUtils.maskEmail("zhangsan@qq.com")    = "zha***@qq.com"
     * </pre>
     *
     * @param email 邮箱
     * @return 隐藏邮箱
     */
    public static String maskEmail(String email) {
        if (email == null) {
            return null;
        }
        email = email.trim();
        int index = email.indexOf('@');
        String userName = email.substring(0, index);
        if (userName.length() < 4) {
            return email.substring(0, index + 1) + "***" + email.substring(email.lastIndexOf('.'));
        }
        userName = userName.substring(0, 3);
        return userName + "***" + email.substring(index);
    }

    /**
     * 隐藏卡号信息
     *
     * @param cardNo 卡号
     * @return 隐藏卡号
     */
    private static String maskCardNo(String cardNo) {
        if (cardNo == null || cardNo.trim().length() <= 8) {
            return cardNo;
        }
        cardNo = cardNo.trim();
        int length = cardNo.length();
        String firstFourNo = cardNo.substring(0, 4);
        String lastFourNo = cardNo.substring(length - 4);
        StringBuilder mask = new StringBuilder(firstFourNo);
        for (int i = 0; i < length - 8; i++) {
            mask.append('*');
        }
        return mask.append(lastFourNo).toString();
    }

    /**
     * 隐藏身份证号码
     *
     * @param idCardNo 身份证号
     * @return 隐藏身份证号
     */
    public static String maskIdCardNo(String idCardNo) {
        return maskCardNo(idCardNo);
    }

    /**
     * 隐藏银行卡号码
     *
     * @param bankCardNo 银行卡号
     * @return 隐藏银行卡号
     */
    public static String maskBankCardNo(String bankCardNo) {
        return maskCardNo(bankCardNo);
    }

}
